package com.myaihui.controller;

import com.belonk.commons.util.date.DateUtils;
import com.belonk.msoffice.excel.util.POIExcelUtil;
import com.myaihui.domain.PMBill;
import com.myaihui.domain.SysUser;
import com.myaihui.foundation.constant.SysConst;
import com.myaihui.foundation.model.Pager;
import com.myaihui.foundation.msg.MsgDefinition;
import com.myaihui.foundation.msg.ResultMsg;
import com.myaihui.foundation.query.PMBillQuery;
import com.myaihui.service.PMBillService;
import com.myaihui.util.LoginUtil;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by sun on 2018/9/8.
 *
 * @author sunfuchang03@126.com
 * @version 1.0
 * @since 1.0
 */
@Controller
@RequestMapping("/pmbill/paid")
public class PMPaidBillController {
    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Static fields/constants/initializer
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    private static Logger log = LoggerFactory.getLogger(PMPaidBillController.class);
    private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
    private static DecimalFormat decimalFormat = new DecimalFormat("#.00");

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Instance fields
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @Autowired
    private PMBillService pmBillService;
    @Value("${bill.export.max.count}")
    private Integer exportMaxCnt;

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Constructors
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */



    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Public Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @GetMapping({"/", ""})
    public String home(Model model) {
        return "pmpaidbill/home";
    }

    @GetMapping("/view/{id}")
    public String edit(@PathVariable String id, Model model) {
        model.addAttribute("bill", pmBillService.getById(id));
        return "pmpaidbill/view";
    }

    @PostMapping("/page")
    @ResponseBody
    public ResultMsg queryPageData(PMBillQuery query) {
        SysUser sysUser = LoginUtil.loginUser();
        if (sysUser.getPlatformType() != SysConst.SubjectType.PROPERTY) {
            return ResultMsg.error("403", "Unauthorized");
        }
//        query.setStatus(SysConst.PMBillState.PAID);
        query.setPropertyMgrId(sysUser.getPlatformId());
        Pager<PMBill> pmBillPager = pmBillService.pageQuery(query);
        return ResultMsg.success(pmBillPager);
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public ResultMsg delete(@PathVariable String id) {
        if (!StringUtils.hasLength(id)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        pmBillService.delete(id);
        return ResultMsg.success(true);
    }

    @RequestMapping(value = "/export")
    public void export(PMBillQuery query, HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        query.setStatus(SysConst.PMBillState.PAID);
        if (exportMaxCnt == null) {
            exportMaxCnt = 3000;
        }
        query.setiDisplayLength(exportMaxCnt);
        query.setOrderField("paidTime"); // 按缴费时间降序
        Pager<PMBill> pmBillPager = pmBillService.pageQuery(query);
        XSSFWorkbook xssfWorkbook = POIExcelUtil.createXSSFWorkbook();
        Sheet sheet = xssfWorkbook.createSheet(LocalDateTime.now().format(dateFormatter).replaceAll("/", "-"));

        // 表头
        String[] headers = {"房号", "住户", "住户手机号", "费用时间", "出账日期", "下发时间",
                "应收金额", "实收金额", "缴费订单号", "缴费时间", "备注"};
        // 表头样式
        XSSFCellStyle headStyle = xssfWorkbook.createCellStyle();
        headStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        Font font = xssfWorkbook.createFont();
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headStyle.setFont(font);
        POIExcelUtil.setHeader(sheet, headers, headStyle);

        List<List<Object>> datas = new LinkedList<>();
        List<PMBill> pmBills = pmBillPager.getAaData();
        int maxCnt = pmBills.size();
        if (maxCnt > exportMaxCnt) {
            maxCnt = exportMaxCnt;
        }
        for (int i = 0; i < maxCnt; i++) {
            PMBill bill = pmBills.get(i);

            List<Object> rowDatas = new LinkedList<>();
            rowDatas.add(bill.getHouseNumber());
            rowDatas.add(bill.getUserName());
            rowDatas.add(bill.getUserMobile());
            rowDatas.add(bill.getDuration());
            rowDatas.add(DateUtils.of(bill.getReleaseTime()).format(dateFormatter));
            Date publishedTime = bill.getPublishTime();
            if (publishedTime != null) {
                rowDatas.add(DateUtils.of(publishedTime).format(dateFormatter));
            } else {
                rowDatas.add(null);
            }

            BigDecimal shouldPayAmount = bill.getTotalAmount();
            if (shouldPayAmount != null) {
                rowDatas.add(decimalFormat.format(shouldPayAmount));
            } else {
                rowDatas.add(null);
            }
            BigDecimal paidAmount = bill.getPaidAmount();
            if (paidAmount != null) {
                rowDatas.add(decimalFormat.format(paidAmount));
            } else {
                rowDatas.add(null);
            }
            rowDatas.add(bill.getPayOrderNo());

            Date paidTime = bill.getPaidTime();
            if (paidTime != null) {
                rowDatas.add(DateUtils.of(paidTime).format(dateFormatter));
            } else {
                rowDatas.add(null);
            }
            rowDatas.add(bill.getRemark());
            datas.add(rowDatas);
        }
        XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        // 设置数据
        POIExcelUtil.setWorkbookData(sheet, datas, cellStyle);

        // 自动列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        resp.setContentType("application/x-download");
        resp.setHeader("Content-Disposition", "attachment; filename=" + new String("已缴账单明细.xlsx".getBytes("utf-8"), "iso-8859-1"));
        xssfWorkbook.write(resp.getOutputStream());
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Private Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */


}